package com.os.sys.common.utility;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by Administrator on 2017/5/26.
 */
public class WebClass {
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        return request;
    }

    public static HttpServletResponse getResponse() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = attributes.getResponse();
        return response;
    }

    // 考虑到可能用了反向代理，这里如果读取到本地ip，需要考虑从反向代理约定好header中读取代理前的ip
    public static String getIP() {
        HttpServletRequest request = getRequest();
        String ip = request.getRemoteAddr();
        if (ip.contains("0:0:0:0") || ip.contains("127.0.0.1")) {
            String nIP = "";
            nIP = request.getHeader("X-Real-IP"); //REVIEW 如果经过多级代理，还需要再处理
            if (StringClass.isNotBlank(nIP)) {
                ip = nIP;
            }
        }
        return ip;
    }

    // 把系统的某个文件给用户下载，如果浏览器支持，可以选择在线打开
    public static void downloadFile(String fileFullName, boolean isOnline) throws IOException {
        HttpServletResponse response = getResponse();
        File f = new File(fileFullName);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;

        response.reset(); // 非常重要
        if (isOnline) { // 在线打开方式
            URL u = new URL("file:///" + fileFullName);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(f.getName(), "utf-8"));
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(f.getName(), "utf-8"));
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.close();
    }

    // 考虑到可能用了反向代理，这里如果读取到host，需要考虑从反向代理约定好header中读取代理前的host
    public static String getHost() {
        HttpServletRequest request = getRequest();
        String host = request.getRemoteHost();
        if (host.contains("localhost") || host.contains("127.0.0.1")) {
            String nHost = "";
            nHost = request.getHeader("X-Host"); //REVIEW 如果经过多级代理，还需要再处理
            if (StringClass.isNotBlank(nHost)) {
                host = nHost;
            }
        }
        return host;
    }

    // 获得基础请求地址
    public static String getBaseUri() {
        HttpServletRequest request = getRequest();
        String path = request.getContextPath();
        String baseUri = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort() + path + "/";

        return baseUri;
    }

    // 页面跳转
    public static void sendRedirect(String url) {
        HttpServletResponse response = getResponse();
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String requestToString(String key) {
        HttpServletRequest request = getRequest();
        String va;
        va = request.getParameter(key);
        if (StringClass.isNullOrEmpty(va)) {
        }
        return va;
    }

    public static int requestToInt(String key) {
        HttpServletRequest request = getRequest();
        String va;
        va = request.getParameter(key);
        if (StringClass.isNullOrEmpty(va)) {

        }
        try {
            return Integer.parseInt(va);
        } catch (Exception ex) {
            return 0;
        }
    }

    public static long requestToLong(String key) {
        HttpServletRequest request = getRequest();
        String va;
        va = request.getParameter(key);
        if (StringClass.isNullOrEmpty(va)) {

        }
        try {
            return Long.valueOf(va);
        } catch (Exception ex) {
            return 0;
        }
    }


}
